
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_class2/1195/personal%20info.dart';
import 'package:flutter_class2/1195/try.dart';
import 'info.dart';
import 'package:flutter_class2/1195/news.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;

class TkPage extends StatefulWidget {
  @override
  _TkPageState createState() => _TkPageState();
}

class _TkPageState extends State<TkPage> with SingleTickerProviderStateMixin{
  News news = News();
  bool _aGet = false;
  int _pageFlag = 0;
  TabController tabController;
  List<String> tabStrings = ['头条新闻',"每日简报"];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    tabController=TabController(length: 2, vsync: this);
    tabController.addListener(() {
      var index = tabController.index;
      var preIndex = tabController.previousIndex;
      print("当前页面：$index，上一页面：$preIndex");
    });
  }


  @override
  Widget build(BuildContext context) {

    final popupMenuEntry = <PopupMenuEntry<String>>[
      PopupMenuItem(value:'0', child:Text('头条新闻')),
      PopupMenuItem(value:'1', child:Text('影视咨询')),
    ];

    final refreshButton = FloatingActionButton(
      tooltip: "刷新",
      child: PopupMenuButton<String>(
        icon: Icon(Icons.list),
        tooltip: "切换频道",
        offset: Offset(0,0),//调节弹出菜单的相对位置
        onSelected: (value){
          setState(() {
            _pageFlag = int.parse(value);
          });
          if(_pageFlag == 0){
            getNews0();
          }else if(_pageFlag == 1){
            getNews1();
          }
        },
        itemBuilder: (context) {
          return popupMenuEntry;
        },
        enableFeedback: true,
      ),
    );

    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.person),
              onPressed: () {
                Navigator.push(
                    context, MaterialPageRoute(builder: (context) => PSPage()));
              },
            ),
            // _popMenu(),
            IconButton(
              icon: Icon(Icons.info_outline),
              onPressed: () {
                Navigator.push(
                    context, MaterialPageRoute(builder: (context) => IFPage()));
              },
            ),
          ],
          backgroundColor: Colors.blueAccent,
          elevation: 0,
          title: Text("CCTB新闻浏览器"),
          centerTitle: true,
          bottom: TabBar(
            controller: tabController,
            labelColor: Colors.white,
            tabs: <Widget>[
              Tab(text: tabStrings[_pageFlag]),
              // Tab(text: "科技资讯"),
              Tab(text: "个人中心"),
              // Tab(text: "影视资讯"),
            ],
          ),
        ),
        body: TabBarView(
          controller: tabController,
            children: [
              Container(
                  // margin: new EdgeInsets.symmetric(vertical: 20.0),
                  height: 200.0,
                  child: _aGet
                      ? ListView.builder(
                    itemBuilder: (context, index) => _buildNewsItem(context, index),
                    itemCount: news.newslist.length,
                  )
                      : Text(
                    '请点击右下角切换新闻频道',
                    style: TextStyle(
                      fontSize: 20.0,
                    ),
                    textAlign: TextAlign.center,
                  )
              ),
              Container(
                height: 200.0,
                child: Center(child:Text('个人中心')),
              ),
            ]
        ),
        // floatingActionButton: FloatingActionButton(
        //     child: Icon(Icons.refresh),
        //     onPressed: (){
        //       if(_pageFlag == 0){
        //         getNews();
        //       }else if (_pageFlag == 1){
        //         getNews2();
        //       }
        //     }
        // ),
        floatingActionButton: refreshButton,
      ),
    );
  }

  Widget _buildNewsItem(BuildContext context, int index) {
    print(news.newslist[index].picUrl);
    return ListTile(
      leading: Container(
        height: 100,
        width: 100,
        child: news.newslist[index].picUrl == null
            ? Image.asset('images/01.jpg', width: 100, height: 100)
        // : Image.network(news.newslist[index].picUrl.replaceAll("http", "https")),
            :Image.network(ccbReplace(news.newslist[index].picUrl)),
        alignment: Alignment.center,
      ),
      title: Text(news.newslist[index].title),
      subtitle: Text(news.newslist[index].ctime.toString()),
      trailing: Icon(Icons.keyboard_arrow_right),
      isThreeLine: false,
      dense: false,
      contentPadding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0),
      enabled: true,
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => CCBNewsDetailPage(
              title: news.newslist[index].title,
              url: news.newslist[index].url.replaceAll("http", "https"),
            )));
      },
      onLongPress: () {
        print('LongPress');
      },
    );
  }

  getNews0() async {
    var response = await http.get(Uri.parse(
        'https://api.tianapi.com/topnews/index?key=31a96af39dc04706c2f56040c2823444&'));// 必须是https
    print("【response】"+response.statusCode.toString());
    if (response.statusCode == 200) {
      setState(() {
        _aGet = true;
        print(News.fromRawJson(response.body).toString());
        news = News.fromRawJson(response.body);
        print(news.toString());
      });
      print("【getNewsSuccess-0】");
      // print(news.toJson());
    }else{
      print("【getNewsFailed-0】");
    }
  }

  getNews1() async {
    var response = await http.get(Uri.parse(

        'https://api.tianapi.com/film/index?key=31a96af39dc04706c2f56040c2823444&'));// 必须是https
    print("【response】"+response.statusCode.toString());
    if (response.statusCode == 200) {
      setState(() {
        _aGet = true;
        print(News.fromRawJson(response.body).toString());
        news = News.fromRawJson(response.body);
        print('8989'+news.toString());

        print('8989'+news.toJson().toString());
      });
      print("【getNewsSuccess-1】");
      // print(news.toJson());
    }else{
      print("【getNewsFailed-1】");
    }
  }

  String ccbReplace(String string){
    if(string.substring(0,5) == "https"){

    }else{
      string = string.replaceAll('http', 'https');
    }
    print("【picUrl】$string");
    return string;
  }



}
